﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Actya.Core.Security;
using Actya.Web.Infrastructure.AntiForgery;

namespace Actya.Web.Controllers.CmsAdmin
{
    public class AccountController : Controller
    {
    	private readonly IMembershipService _membershipService;

		public AccountController(IMembershipService membershipService)
		{
			_membershipService = membershipService;
		}

    	public ActionResult Login(string returnUrl)
        {
        	ViewBag.ReturnUrl = returnUrl;
			if (Request.IsAjaxRequest())
			{
				return PartialView();
			}
			else
			{
				return View();				
			}
        }

		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Login(string username, string password, string returnUrl)
		{
			try
			{
				var user = _membershipService.AuthenticateUser(username, password);
				if (user.IsAuthenticated)
				{
					FormsAuthentication.SetAuthCookie(username, false);
					if (! String.IsNullOrEmpty(returnUrl))
					{
						return Redirect(returnUrl);
					}
					else
					{
						return RedirectToAction("Index", "Pages");
					}
				}
				else
				{
					ModelState.AddModelError("", "Invalid username/password combination.");
				}
			}
			catch (Exception ex)
			{
				ModelState.AddModelError("", ex);
			}
			ViewBag.Username = username;
			ViewBag.ReturnUrl = returnUrl;
			return View();
		}

		[HttpPost]
		[AjaxValidateAntiForgeryToken]
		public ActionResult AjaxLogin(string username, string password, string returnUrl)
		{
			try
			{
				var user = _membershipService.AuthenticateUser(username, password);
				if (user.IsAuthenticated)
				{
					FormsAuthentication.SetAuthCookie(username, false);
					return Json(new { success = true, redirect = returnUrl });
				}
				ModelState.AddModelError("", "Invalid username/password combination.");
			}
			catch (Exception ex)
			{
				ModelState.AddModelError("", ex);
			}
			return Json(new { errors = ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage)) });
		}

		[Authorize]
		public ActionResult Logout()
		{
			FormsAuthentication.SignOut();
			return Redirect("~/");
		}
    }
}
